<?php
declare (strict_types=1);

namespace app\shop\command;

use app\shop\enums\order\OrderCrontabType;
use app\shop\library\ShopLogHelper;
use app\shop\model\order\OrderCrontabModel;
use app\shop\service\OrderService;
use Exception;
use think\console\Command;
use think\console\Input;
use think\console\Output;

class AutoCancelOrder extends Command
{
    protected function configure(): void
    {
        // 指令配置
        $this->setName('auto_cancel_order')->setDescription('Auto Cancel unpaid Order');
    }

    protected function execute(Input $input, Output $output): void
    {
        $className = get_class();

        $orderIds = OrderCrontabModel::where([
            ['time', '<=', time()],
            ['action', '=', OrderCrontabType::ORDER_CANCEL]
        ])->column('order_id');

        if (empty($orderIds)) {
            ShopLogHelper::info("自定义命令【 $className 】执行完毕", ['msg' => '没有需要自动取消的订单']);
            return;
        }

        $successData = [];
        $failData    = [];

        $orderService = new OrderService();
        foreach ($orderIds as $orderId) {
            try {
                $orderService->autoCancel($orderId);
                $successData[] = ['order_id' => $orderIds];
            } catch (Exception $e) {
                $failData[] = ['order_id' => $orderId, 'err' => $e->getMessage()];
            }
        }

        if ($successData) {
            ShopLogHelper::info("自定义命令【 $className 】执行成功", $successData);
        }

        if ($failData) {
            ShopLogHelper::error("自定义命令【 $className 】执行失败", $failData);
        }
    }
}
